import React, { useState } from 'react';
import { Modal, Form, Input, message } from 'antd';
import PropTypes from 'prop-types';
// import { setRouteInfo } from '@api/networkConfig';
import { addNode, updateNode } from '@api/nodes';
// import { _ } from 'core-js';
import { IP_RE } from '@util/constants';
import { ORGANIZATION_RE32 } from '@util/constants';
import { useEffect } from 'react';
const { confirm } = Modal;
// const { Option } = Select;
const formItemLayout = {
  labelCol: {
    span: 3
  },
  wrapperCol: {
    span: 21
  }
};
function EditModal(props) {
  const { form, detail, visible } = props;
  const { getFieldDecorator, validateFields, setFieldsValue } = form;
  const [confirmLoading, setConfirmLoading] = useState(false);
  // console.log(props);
  // 重制
  const onReset = () => {
    form.resetFields();
  };
  const onCancel = () => {
    onReset();
    props.onCancel();
  };
  const sureModel = values => {
    confirm({
      title: '确定修改节点IP?该扫描节点正在执行的任务将受到影响',
      className: 'system-update-confirm-modal',
      okText: '确定',
      cancelText: '取消',
      width: '500px',
      onOk() {
        // eslint-disable-next-line no-use-before-define
        nodeApi(values);
      },
      onCancel() {}
    });
  };
  const nodeApi = async values => {
    delete values.to;
    const edit = detail.device_id;
    const api = edit ? updateNode : addNode;
    const data = edit
      ? { ...values, origin_node_ip: detail.node_ip, node_role: detail.node_role }
      : { nodes: [{ ...values }] };
    // 如果是修改并且是master不传node_ip
    if (detail.node_role === 'master' && edit) {
      delete data.node_ip;
    }
    try {
      setConfirmLoading(true);
      await api(data);
      message.success('操作成功');
      onReset();
      props.onOk();
    } catch ({ response }) {
      message.error(response?.data?.error_code || '操作失败');
    }
    setConfirmLoading(false);
  };

  const onOk = () => {
    return validateFields(async (err, values) => {
      const edit = detail.device_id;
      if (!err) {
        if (edit && detail.node_role !== 'master' && detail.node_ip !== values.node_ip) {
          sureModel(values);
        } else {
          nodeApi(values);
        }
      }
    });
  };
  useEffect(() => {
    if (visible) {
      setFieldsValue({ to: detail.node_role === 'master' ? '管理节点' : '扫描节点' });
    }
    if (detail) {
      setFieldsValue(detail);
    }
  }, [visible]);

  return (
    <>
      <Modal
        title={detail.device_id ? '修改节点' : '添加节点'}
        {...props}
        onOk={onOk}
        onCancel={onCancel}
        maskClosable={false}
        confirmLoading={confirmLoading}
      >
        <Form labelAlign="left">
          <Form.Item {...formItemLayout} label="名称" colon={false}>
            {getFieldDecorator('node_name', {
              rules: [
                {
                  required: true,
                  message: '请输入名称'
                },
                {
                  min: 2,
                  message: '请输入中文、英文或数字、字符长度不小于2且不超过32位'
                },
                {
                  pattern: ORGANIZATION_RE32,
                  message: '请输入中文、英文或数字、字符长度不小于2且不超过32位'
                }
              ]
            })(<Input placeholder="请输入中文、英文或数字、字符长度不小于2且不超过32位" />)}
          </Form.Item>
          <Form.Item {...formItemLayout} label="IP" colon={false}>
            {getFieldDecorator('node_ip', {
              rules: [
                {
                  required: true,
                  message: '请输入ip'
                },
                {
                  pattern: IP_RE,
                  message: 'IP格式错误'
                }
              ]
            })(<Input disabled={detail.node_role === 'master'} placeholder="请输入节点IP" />)}
          </Form.Item>
          <Form.Item {...formItemLayout} label="类型" colon={false}>
            {getFieldDecorator('to', {
              rules: [
                {
                  required: true,
                  message: '请选择类型'
                }
              ]
              // validateFirst: true
            })(<Input placeholder="请输入节点IP" disabled={true} />)}
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
}
EditModal.propTypes = {
  visible: PropTypes.bool,
  onOk: PropTypes.func,
  onCancel: PropTypes.func,
  detail: PropTypes.object,
  form: PropTypes
};
export default Form.create()(EditModal);
